package com.fr.lintcode;

import java.util.ArrayList;
import java.util.Stack;

import org.junit.Test;

/**
*作者：furong
*日期：2017年1月17日
*时间：下午6:55:19
*/
public class Q95 {
    /**
     * @param root: The root of binary tree.
     * @return: True if the binary tree is BST, or false
     */
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        ArrayList<Integer> rs = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode t = root;
        while (t != null || !stack.isEmpty()) {
            while (t != null) {
                stack.push(t);
                t = t.left;
            }
            if (!stack.isEmpty()) {
                t = stack.pop();
                rs.add(t.val);
                t = t.right;
            }
        }
        for (int i = 0; i < rs.size() - 1; i++) {
            if (rs.get(i) >= rs.get(i + 1)) {
                return false;
            }
        }
        return true;
    }

    @Test
    public void testA() {
        TreeNode root = new TreeNode(5);
        TreeNode r1 = new TreeNode(3);
        TreeNode r2 = new TreeNode(8);
        TreeNode r3 = new TreeNode(1);
        TreeNode r4 = new TreeNode(2);
        TreeNode r5 = new TreeNode(2);
        root.left = r1;
        root.right = r2;
        r1.left = r3;
        r2.right = r5;
        r3.right = r4;
        System.out.println(isValidBST(root));
    }
}
